﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ShootMan
{
    [RequireComponent(typeof(Rigidbody))]
    public class DefaultPlayerController : MonoBehaviour
    {
        [shaco.ReadOnly]
        public string playerID = "";
        [SerializeField]
        private TextMesh _textPlayerID = null;
        [SerializeField]
        private float _shootInterval = 0.5f;

        private ShootMan.cfg_hero_attributes.RowData _heroData = null;
        private Rigidbody _rigidbody = null;
        private GameLayer _gameLayer = null;
        private Vector3 _oldPos = Vector3.zero;
        private bool _isGameNetLayerInited = false;
        private float _shootTimer;

        private void Awake()
        {
            _shootTimer = _shootInterval;
            _rigidbody = this.GetComponent<Rigidbody>();
            _heroData = ShootMan.cfg_hero_attributes.Get(0);
            _textPlayerID.text = playerID.ToString();

            this.AddOnceEvent<shaco.UIStateChangedEvents.OnUIOpenEndEvent<GameNetLayer>>((sender, arg) =>
            {
                _isGameNetLayerInited = true;
            });
        }

        void FixedUpdate()
        {
            if (!_isGameNetLayerInited)
                return;

            if (_oldPos != this.transform.position)
            {
                _oldPos = this.transform.position;
                SyncTransformPosition();
            }
        }

        private void Update()
        {
            if (playerID != UserData.playerID)
                return;

            _shootTimer += Time.deltaTime;

            if (Input.GetKey(KeyCode.UpArrow))
                MoveUp();
            if (Input.GetKey(KeyCode.DownArrow))
                MoveDown();
            if (Input.GetKey(KeyCode.LeftArrow))
                MoveLeft();
            if (Input.GetKey(KeyCode.RightArrow))
                MoveRight();

            if (Input.GetKey(KeyCode.Space))
                Shoot();

            if (Input.touchCount > 0)
            {
                var touchesTmp = Input.touches;
                OnTouchEvent(touchesTmp[0].position);
            }

            if (Input.GetMouseButton(0))
                OnTouchEvent(Input.mousePosition);
        }

        private void OnTouchEvent(Vector2 position)
        {
            if (playerID != UserData.playerID)
                return;

            var widthHalf = Screen.width / 2;
            var heightHalf = Screen.height / 4;
            if (position.x < widthHalf)
                MoveLeft();
            else
                MoveRight();

            if (position.y < heightHalf)
                Shoot();
        }

        public void MoveUp()
        {
            this.transform.Translate(0, 0, _heroData.MOVE_SPEED);
        }

        public void MoveDown()
        {
            this.transform.Translate(0, 0, -_heroData.MOVE_SPEED);
        }

        public void MoveLeft()
        {
            this.transform.Translate(-_heroData.MOVE_SPEED, 0, 0);
        }

        public void MoveRight()
        {
            this.transform.Translate(_heroData.MOVE_SPEED, 0, 0);
        }

        public void Shoot()
        {
            //@@@游戏登录联网移动都ok，不过当游戏结束时候没同时结束(需要加1个结束通知)，另外目前结束情况下会出现endlayer脚本丢失错误暂不清楚原因

            //游戏是否已经结束
            if (null == _gameLayer)
                _gameLayer = shaco.GameHelper.ui.GetUIComponent(typeof(GameLayer)) as GameLayer;
            if (_gameLayer.isGameOver)
                return;
            // if (_gameLayer.GetLuaParam<bool>("isGameOver"))
            //     return;

            if (_shootTimer < _shootInterval)
                return;
            _shootTimer = 0;

            //创建一颗子弹向前飞行
            var bulletComponent = shaco.GameHelper.objectpool.Instantiate(() =>
            {
                var obj = shaco.GameHelper.res.LoadEx<GameObject>($"{GlobalDefines.HOTUPDATE_ROOT}Prefabs/Bullets/default_bullet.prefab");
                return obj.GetComponent<DefaultBulletController>();
            });

            bulletComponent.transform.position = this.transform.position;
            bulletComponent.moveDirection = this.transform.forward * _heroData.SHOOT_SPEED;

            this.InvokeEvent(new ShootBulletCountRecordEvent()
            {
                shootCount = 1
            });

            SyncShootBullet();
        }

        private void SyncTransformPosition()
        {
            if (playerID != UserData.playerID)
                return;

            var eventTmp = shaco.GameHelper.objectpool.Instantiate(() => new SyncTransformPositionNetEvent());
            eventTmp.position = this.transform.position;
            this.InvokeEvent(eventTmp);
            eventTmp.RecyclingWithPool();
        }

        private void SyncShootBullet()
        {
            if (playerID != UserData.playerID)
                return;

            var eventTmp = shaco.GameHelper.objectpool.Instantiate(() => new SyncShootBulletNetEvent()
            {
                shootCount = 1
            });
            this.InvokeEvent(eventTmp);
            eventTmp.RecyclingWithPool();
        }
    }
}